package com.jx.service.impl;

import com.jx.common.CustomException;
import com.jx.dao.UserMapper;
import com.jx.pojo.User;
import com.jx.service.UserService;
import com.jx.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public void userRegister(User user) {
        // 1.查询用户名是否已经存在
        User result = userMapper.findByPhone(user.getPhone());
        if(result != null) {
            throw new CustomException("手机号已被占用");
        }
        // 2.对密码进行加密
        String salt = UUID.randomUUID().toString().toUpperCase(); // 盐值
        String md5Password = getMd5Password(user.getPassword(), salt); // 加密
        // 3.将盐值和加密后的密码设置到user对象中
        user.setPassword(md5Password);
        user.setSalt(salt);
        // 4.生成token
        String token = TokenUtil.generateToken(user);
        user.setToken(token);
        // 4.注册用户
        Integer rows = userMapper.userRegister(user);
        // 判断注册是否成功
        if (rows != 1) {
            throw new CustomException("注册失败");
        }
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public User userLogin(User user) {
        // 1.查询用户名是否已经存在
        User result = userMapper.findByPhone(user.getPhone());
        if(result == null) {
            throw new CustomException("用户名不存在");
        }
        // 2.从查询结果中获取盐值对密码进行加密
        String salt = result.getSalt();
        String md5Password = getMd5Password(user.getPassword(), salt);
        user.setPassword(md5Password);
        // 3.从查询结果中获取密码进行比对
        String password = result.getPassword();
        if(!password.equals(user.getPassword())) {
            throw new CustomException("用户名或密码错误");
        }
        // 4.返回用户信息
//        User user1 = userMapper.userLogin(user);
        return result;
    }

    /**
     * 根据token查询用户信息
     * @param token
     * @return
     */
    @Override
    public User getUserInfoByToken(String token) {
        User user = userMapper.getUserInfoByToken(token);
        if(user == null) {
            throw new CustomException("无效token");
        }
        return user;
    }


    /**
     * MD5算法对密码进行加密
     * @param password
     * @param salt
     * @return
     */
    private String getMd5Password(String password, String salt) {
        // 使用MD5算法加密三次
        for(int i=0;i<3;i++) {
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }
}
